<?php
namespace support;

use support\exception\Exception;
use think\db\Query;
use think\Model as BaseModel;

/**
 * Class Model
 * @package support
 */
abstract class Model extends BaseModel
{
    protected $autoWriteTimestamp = 'int';
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    protected $datetime_format = false;

    /**
     * 模型验证(错误直接抛出异常)
     * @param $className
     * @param array $data
     * @param string|null $scene
     * @return bool
     * @throws Exception
     */
    public function validate($className , $data = [] ,  string $scene = null)
    {
        if(class_exists($className)){
            /**
             * @param \bang\validate\Validate $validateObject
             */
            $validateObject = new $className;
            if(!empty($scene)){
                if(!$validateObject->scene($scene)->check($data)){
                    throw new Exception($validateObject->getError());
                }
            }else{
                if(!$validateObject->check($data)){
                    throw new Exception($validateObject->getError());
                }
            }
        }else{
            throw new Exception("Class " . $className . " not found");
        }
        return true;
    }

    /**
     * 判断记录是否存在
     * @param array $option
     * @return bool
     */
    public function isExistRecord($option = []) :bool
    {
        $ret = $this->where($option)->count();
        return $ret > 0 ? true : false;
    }

    /**
     * 删除记录
     * @param array $option
     * @return bool
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function deleteRecord($option = []) : bool
    {
        $list = $this->where($option)->select();
        foreach ($list as $v){
            $res = $v->delete();
            if($res === false){
                throw new Exception("删除失败");
            }
            unset($res);
        }
        return true;
    }


    /**
     * 获取数据
     * @param $data
     * @param array $with
     * @param bool $cache
     * @return array|BaseModel|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get( $data , $with = [], $cache = false)
    {
        if (is_null($data)) {
            return null;
        }

        if (true === $with || is_int($with)) {
            $cache = $with;
            $with = [];
        }
        $query = static::parseQuery($data, $with, $cache);
        return $query->find($data);
    }


    /**
     * 分析查询表达式.
     *
     * @param mixed  $data  主键列表或者查询条件（闭包）
     * @param string $with  关联预查询
     * @param bool   $cache 是否缓存
     *
     * @return Query
     */
    protected static function parseQuery(&$data, $with, $cache)
    {
        $result = self::withJoin($with)->cache($cache);
        if (is_array($data) && key($data) !== 0) {
            $result = $result->where($data);
            $data = null;
        } elseif ($data instanceof \Closure) {
            call_user_func_array($data, [&$result]);
            $data = null;
        } elseif ($data instanceof Query) {
            $result = $data->withJoin($with)->cache($cache);
            $data = null;
        }

        return $result;
    }


}